#include "Stack.h"

void StackInit(ST* ps)
{
	assert(ps);
	ps->p = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

void StackDestroy(ST* ps)
{
	assert(ps);
	if (ps->p)//如果p为NULL，不可以free
	{
		free(ps->p);
	}
	ps->p= NULL; //free后置空，避免野指针问题
	ps->top = 0;
	ps->capacity = 0;
}

void StackPush(ST* ps, STDatatype x)
{
	assert(ps);

	// 检查空间够不够，不够就增容
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDatatype* tmp = realloc(ps->p, sizeof(STDatatype)*newcapacity);
		ps->p= tmp;
		ps->capacity = newcapacity;
	}

	ps->p[ps->top] = x;
	ps->top++;
}

bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;//->优先级高于--
}

int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}

STDatatype StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->p[ps->top - 1];
}
